package bar.dark.lee.select;

import java.util.ArrayList;
import java.util.Calendar;

import org.apache.http.impl.client.DefaultProxyAuthenticationHandler;

import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.style.UnderlineSpan;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.TableLayout;
import android.widget.TableLayout.LayoutParams;
import android.widget.TableRow;
import android.widget.TextView;
import bar.dark.lee.R;
import bar.dark.lee.SuperActivity;
import bar.dark.lee.common.BDTextView;
import bar.dark.lee.common.BDUtil;
import bar.dark.lee.common.DBSQLite;
import bar.dark.lee.common.DBSQLite.ParseSelectData;
import bar.dark.lee.setting.TipInfoActivity;
import bar.dark.lee.setting.TipsActivity;

public class SelectCalenderActivity extends SuperActivity implements OnClickListener, OnTouchListener
{
	private ImageButton    pre,next;
	private Button okButton;
	private ArrayList<TextView> tempList = new ArrayList<TextView>();
	private ArrayList<TextView> list = new ArrayList<TextView>();
	
	private TextView    today,time;
	private TableLayout table;
	int     setYear;
	int     setMonth;
	int     setMonth2;
	int     setDay;
	
	private ArrayList<String> selectDate = new ArrayList<String>();
	private ArrayList<PositionClass> positionList = new ArrayList<PositionClass>();
	private String selectMonth = "";
	int tableLayoutWidth;
	int tableLayoutHeight;
	
	boolean firstRun = true;
	
	private ArrayList<CheckDate> totalSelect = new ArrayList<CheckDate>();
	
	private ArrayList<String> dbData = new ArrayList<String>();
	
	int colorSelect;
	
	private DBSQLite sql;
	
	private int defaultPaintFlag;
	
	
	private class PositionClass {
		
		private int left;
		private int top;
		private int right;
		private int bottom;
			
		public PositionClass(int left, int right, int top, int bottom) {
			this.left = left;
			this.top = top;
			this.right = right;
			this.bottom = bottom;
		}

		public int getLeft() {
			return left;
		}

		public void setLeft(int left) {
			this.left = left;
		}

		public int getTop() {
			return top;
		}

		public void setTop(int top) {
			this.top = top;
		}

		public int getRight() {
			return right;
		}

		public void setRight(int right) {
			this.right = right;
		}

		public int getBottom() {
			return bottom;
		}

		public void setBottom(int bottom) {
			this.bottom = bottom;
		}
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) 
	{
		isAdFlag = false;
		
		super.onCreate(savedInstanceState);
		setContentView(R.layout.select_calender_activity);
		
		sql = DBSQLite.getInstance(this);
		
		setTitle("내역 달력 조회");
		
		pre = (ImageButton) findViewById(R.id.pre);
		next = (ImageButton) findViewById(R.id.next);
		okButton = (Button) findViewById(R.id.ok);
		today = (TextView) findViewById(R.id.today);
		time = (TextView) findViewById(R.id.time);
		Calendar calendar = Calendar.getInstance();
		setYear = calendar.get(Calendar.YEAR);
		setMonth = calendar.get(Calendar.MONTH);
		setMonth2 = calendar.get(Calendar.MONTH) + 1;
		setDay = calendar.get(Calendar.DAY_OF_MONTH);
		time.setText("오늘은  " + setYear + "년  " + setMonth2 + "월  " + setDay
				+ "일 입니다.");
		
		table = (TableLayout) findViewById(R.id.table);
		for (int i = 0; i < 6; i++) {
			TableRow tr = new TableRow(this);
			for (int j = 0; j < 7; j++) {
				BDTextView tv = new BDTextView(this);
				if (j == 0) {
					tv.setTextColor(Color.RED);
					tv.setTextSize(20);
				} else if (j == 6) {
					tv.setTextColor(Color.BLUE);
					tv.setTextSize(20);
				} else {
					tv.setTextColor(Color.BLACK);
					tv.setTextSize(20);
				}
				tv.setMinimumHeight(BDUtil.dipToPixel(this, 45));
				tv.setGravity(Gravity.CENTER);
				tr.addView(tv);
				tempList.add(tv);
				tv.setOnClickListener(this);
				//tv.setOnTouchListener(this);
				
			}
			table.addView(tr);
		}

		table.setStretchAllColumns(true);
		//table = (TableLayout) findViewById(R.id.week);
		//table.setOnTouchListener(this);
		findViewById(R.id.frame).setOnTouchListener(this);
		View view = new View(this);
		view.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
		view.setOnTouchListener(this);
		((FrameLayout)findViewById(R.id.frame)).addView(view);

		setCalendar(setYear, setMonth);

		pre.setOnClickListener(this);
		next.setOnClickListener(this);
		okButton.setOnClickListener(this);
		findViewById(R.id.reset).setOnClickListener(this);
		
		colorSelect = getResources().getColor(R.color.selectCalendar);
		
		defaultPaintFlag = tempList.get(0).getPaintFlags();
	}
	
	private void setSelectDayData(int year, int month)
	{
		dbData.clear();
		
		String query = "SELECT date FROM in_out";
		
		query = query + getDateForMonth(year, month);
		
		sql.selectMapTile(this, query + " ORDER BY date ASC;", new ParseSelectData() {
			
			@Override
			public void resultData(Cursor c) {
				int columnIndex = c.getColumnIndex("date");
				c.moveToFirst();
				for (int i = 0; i < c.getCount(); i++)
				{
					dbData.add((c.getInt(columnIndex)+"").substring(6, 8));
					c.moveToNext();
				}
			}
		});
	}
	
	private String getDateForMonth(int year, int month) 
	{
		String m = "" + (month+1);
		
		if (month+1 < 10) 
		{
			m = "0" + (m);
		}
		
		String date = year+"" + m;
		String query = " WHERE date >= " + (date+"01") + " and date <= " + (date+"31") + " ";
		return query;
	}
	
	private void setCalendar(int year, int month) 
	{
		if (list.size() > 0) 
		{
			for (int i = 0; i < list.size(); i++) 
			{
				list.get(i).setBackgroundColor(0);
				list.get(i).setPaintFlags(defaultPaintFlag);
			}
		}	
		
		list.clear();
		
		setSelectDayData(year, month);
		
		Calendar calendar = Calendar.getInstance();
		calendar.set(Calendar.YEAR, year);
		calendar.set(Calendar.MONTH, month);
		calendar.set(Calendar.DAY_OF_MONTH, 1);

		today.setText(year + "년 " + (month + 1) + "월");

		int getDay = calendar.get(Calendar.DAY_OF_WEEK);

		int j = 1;
		for (int i = 0; i < tempList.size(); i++) {
			tempList.get(i).setText("");
		}

		boolean flag = true;
		
		for (int i = getDay - 1; i < calendar
				.getActualMaximum(Calendar.DAY_OF_MONTH) + getDay - 1; i++) 
		{
			TextView temp = new TextView(this);
			temp = tempList.get(i);
			list.add(temp);
			for (int k=0; k<dbData.size(); k++) 
			{
				if (j == Integer.parseInt(dbData.get(k))) 
				{
					//temp.setHighlightColor(getResources().getColor(R.color.pink));
					temp.setPaintFlags(temp.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
					temp.setText(j + "");
					flag = false;
					break;
				}
			}
			
			if (flag) 
			{
				temp.setText(j + "");
			}
			
			flag = true;
			j++;
		}
		
		checkBeforeSave();
		
		firstRun = true;
	}

	@Override
	public void onClick(View v) 
	{
		if (v.getId() == R.id.pre) 
		{
			checkSelectedDate();
			saveThisMonth();
			
			setMonth--;
			if (setMonth < 0) 
			{
				setYear--;
				setMonth = 11;
			}
			
			setCalendar(setYear, setMonth);
		} 
		else if (v.getId() == R.id.next) 
		{
			
			checkSelectedDate();
			saveThisMonth();
			
			setMonth++;
			if (setMonth > 11) 
			{
				setMonth = 0;
				setYear++;
			}
			
			setCalendar(setYear, setMonth);
		} 
		else if (v.getId() == R.id.ok) 
		{
			checkSelectedDate();
			saveThisMonth();
			
			if (totalSelect.size() == 0) 
			{
				BDUtil.showDialog(this, "입력 오류", "선택된 조회 날짜가 없습니다.");
				return;
			}
			
			Intent intent = new Intent(this, SelectActivity.class);
			intent.putExtra("TotalSelect", totalSelect);
			startActivity(intent);
			
//			selectMonth = setMonth2+"";
//			for (int i=0; i<selectDate.size(); i++) {
//				Log.e("222222", selectMonth+"/"+selectDate.get(i));
//			}
//			Intent intent = new Intent(this, SelectActivity3.class);
//			intent.putExtra("SelectMonth", setMonth2+"");
//			intent.putStringArrayListExtra("SelectDate", selectDate);
		}
		else if (v.getId() == R.id.reset) 
		{
			
			totalSelect.clear();
			selectDate.clear();
			
			for (int i=0; i<list.size(); i++) 
			{
				list.get(i).setBackgroundColor(0);
			}
			
			if (totalSelect.size() == 0) 
			{
				BDUtil.showDialog(this, "초기화 완료", "날짜 선택을 초기화 했습니다.");
				return;
			}
		}
	}
	
	
	boolean colorChangeFlag = true;
	int changedIndex = -1;
	
	@Override
	public boolean onTouch(View v, MotionEvent event) 
	{
		if (firstRun) 
		{
			positionList.clear();
			
			for (int i=0; i<list.size(); i++) 
			{
				TextView tv = list.get(i);
				
				if (!tv.getText().toString().equals("")) 
				{
					positionList.add(new PositionClass(tv.getLeft(), tv.getRight(), ((View)tv.getParent()).getTop(), ((View)tv.getParent()).getBottom()));
					//Log.e("111", tv.getText().toString()+","+tv.getLeft()+","+tv.getRight()+","+((View)tv.getParent()).getTop()+","+((View)tv.getParent()).getBottom());
				}
			}
			
			firstRun = false;
		}
		
		final int action = event.getAction();
		
	    switch (action) 
	    {
		    case MotionEvent.ACTION_DOWN: 
		    {
		    	final float x = event.getX();
		        final float y = event.getY();
		        
		        for (int i=0; i<positionList.size(); i++) 
		        {
		        	if (changedIndex == i) 
		        	{
		        		continue;
		        	}
		        	
		        	PositionClass position = positionList.get(i);
		        	if (position.getLeft() < x && x < position.getRight() && position.getTop() < y && y <position.getBottom()) {
		        		//Log.e("111", "match ok : "+i);
		        		//Log.e("111", list.get(i).getText().toString()+","+list.get(i).getLeft()+","+list.get(i).getRight()+","+((View)list.get(i).getParent()).getTop()+","+((View)list.get(i).getParent()).getBottom());
		        		//Log.e("111", position.getLeft()+","+position.getRight()+","+position.getTop()+","+position.getBottom());
		        		
		        		changedIndex = i;
		        		
		        		TextView view = list.get(i);
						view.buildDrawingCache();
						Bitmap bitmap = view.getDrawingCache();
						int color = bitmap.getPixel(0, 0);
						//Log.e("ChecktedText","Background Color: " + color);
						view.destroyDrawingCache();
						
		        		if (color == 0)
		        		{
		        			list.get(i).setBackgroundColor(colorSelect);
		        		}
		        		else 
		        		{
		        			list.get(i).setBackgroundColor(0);
		        		}
		        	}
		        }
		        break;
		    }
		        
		    case MotionEvent.ACTION_MOVE: 
		    {
		        final float x = event.getX();
		        final float y = event.getY();
		        for (int i = 0; i < positionList.size(); i++) 
		        {
		        	if (changedIndex == i) 
		        	{
		        		continue;
		        	}
		        	
		        	PositionClass position = positionList.get(i);
		        	if (position.getLeft() < x && x < position.getRight() && position.getTop() < y && y <position.getBottom()) {
		        		//Log.e("111", "match ok : "+i);
		        		//Log.e("111", list.get(i).getText().toString()+","+list.get(i).getLeft()+","+list.get(i).getRight()+","+((View)list.get(i).getParent()).getTop()+","+((View)list.get(i).getParent()).getBottom());
		        		//Log.e("111", position.getLeft()+","+position.getRight()+","+position.getTop()+","+position.getBottom());
		        		
		        		changedIndex = i;
		        		
		        		TextView view = list.get(i);
						view.buildDrawingCache();
						Bitmap bitmap = view.getDrawingCache();
						int color = bitmap.getPixel(0, 0);
						//Log.e("ChecktedText","Background Color: " + color);
						view.destroyDrawingCache();
						
						if (color == 0)
						{
		        			list.get(i).setBackgroundColor(colorSelect);
						}
		        		else
		        		{
		        			list.get(i).setBackgroundColor(0);
		        		}
		        	}
		        }
		        
		        break;
		    }
		    
		    case MotionEvent.ACTION_UP:
		    	changedIndex = -1;
		    	break;
	    }
	    
	    return true;
	}
	
	/**
	 * 현재 달력에 체크된 날짜를 체크해 저장한다.
	 */
	private void checkSelectedDate() 
	{
		selectDate.clear();
		
		TextView view = null;
		Bitmap bitmap = null;
		int color = 0;
		
		for (int i=0; i < list.size(); i++) 
		{
			view = list.get(i);
			view.buildDrawingCache();
			bitmap = view.getDrawingCache();
			color = bitmap.getPixel(0, 0);
			//Log.e("ChecktedText","Background Color: " + color);
			view.destroyDrawingCache();
			
			if (color != 0) 
			{
				// 색칠되어있는것.
				selectDate.add(view.getText().toString());
			}
		}
		
//		for (int i=0; i<selectDate.size(); i++) {
//			Log.e("11111111", selectDate.get(i));
//		}
	}
	
	/**
	 * 이전에 저장해 놓은 내용을 불러온다.
	 */
	private void checkBeforeSave() 
	{
		selectDate.clear();
		
		for (int i=0; i<totalSelect.size(); i++) 
		{
			if (setMonth+1 == totalSelect.get(i).getMonth()) 
			{
				selectDate.addAll(totalSelect.get(i).getSelectDate());
//				for (int j=0; j<totalSelect.get(i).getSelectDate().size(); j++) {
//					selectDate.add(totalSelect.get(i).getSelectDate().get(j));
//				}
			}
		}
		
		for (int i=0; i<selectDate.size(); i++) {
			list.get(Integer.parseInt(selectDate.get(i))-1).setBackgroundColor(colorSelect);
		}
	}
	
	/**
	 * 현재 달력에 체크된 날짜를 저장한다.
	 */
	private void saveThisMonth() 
	{
		if (totalSelect.size() == 0) 
		{
			if (selectDate.size() != 0) 
			{
				totalSelect.add(new CheckDate(setYear, setMonth+1, selectDate));
			}
		} 
		else 
		{
			for (int i=0; i < totalSelect.size(); i++) 
			{
				if (totalSelect.get(i).getYear() == setYear 
						&& totalSelect.get(i).getMonth() == setMonth+1) 
				{
					if (selectDate.size() > 0)
					{
						totalSelect.set(i, new CheckDate(setYear, setMonth+1, selectDate));
					}
					else
					{
						totalSelect.remove(i);
						
						ArrayList<CheckDate> tempList = new ArrayList<CheckDate>();
						tempList.addAll(totalSelect);
						totalSelect.clear();
						totalSelect.addAll(tempList);
					}
					return;
				}
			}
			
			if (selectDate.size() > 0)
			{
				totalSelect.add(new CheckDate(setYear, setMonth+1, selectDate));
			}
		}
	}

	@Override
	protected void tipButton()
	{
		Intent intent = new Intent(this, TipInfoActivity.class);
		intent.putExtra(TipsActivity.TIP_REQUEST_KEY, TipsActivity.TIP_SELECT);
		startActivity(intent);
	}
}
